using System;
using System.Threading.Tasks;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Bda.V20200324;
using TencentCloud.Bda.V20200324.Models;
using System.IO;
using System.Drawing;
using _JsonRealizer;
using project1113.Wrold;
using project1113.SomeTools;
using System.Windows;
using project1113.iniParser;
using project1113.observer;

namespace project1113.Security
{   /// <summary>
/// SecurityGuarder Demo:
/// await Task.Run(() => securityGuarder.Update(img));//不阻塞UI的
/// securityGuarder.Update(img)阻塞的
/// </summary>
    public class SecurityGuarder
    {
        private bool _isRun = true; //启动就打开
        public  SecurityGuarder()
        {
            Bitmap frame;
            SecurityGuarder_Init();
            Task.Run(() => 
            {
                while (true)
                { 
                    try
                    {
                        if(_isRun)
                        {
                            frame = WorldModel.CurrentWorld.Camera.OutputBitmap;

                            if (frame != null)
                            {
                                frame = frame.Clone() as Bitmap;
                                frame.Save("photo.jpg");
                                frame.Dispose();
                                req.Image = GetBase64str(); ;// File.OpenText("myphoto").ReadToEnd();//
                                req.LocalBodySwitch = false;
                                // 返回的resp是一个DetectBodyJointsResponse的实例，与请求对象对应
                                DetectBodyJointsResponse resp = client.DetectBodyJointsSync(req);
                                // 输出json格式的字符串回包                
                                _last_issafe = JsonRealizer.GetRootObject(AbstractModel.ToJsonString(resp));

                            }
                        }
                       
                    }
                    catch (Exception e)
                    {
                        _last_issafe = true;
                    }
                }

            }
            );
        }
        private Task<bool> issafe;
        private static  bool _last_issafe=true;     
        private static ClientProfile clientProfile;
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        private static HttpProfile httpProfile;       
        // 实例化要请求产品的client对象,clientProfile是可选的
        private static BdaClient client;
        // 实例化一个请求对象,每个接口都会对应一个request对象
        private static DetectBodyJointsRequest req = new DetectBodyJointsRequest();

     
       

        private static string GetBase64str()
        {
            FileStream fs = File.OpenRead("photo.jpg"); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组 
            fs.Read(image, 0, filelength); //按字节流读取 
                                           //System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();

            string imgData64 = Convert.ToBase64String(image);// File.OpenText("basestr.txt").ReadToEnd();// // //;
            return imgData64;
        }

        private  void SecurityGuarder_Init()
        {
            string iniFilePath = @"conf\SecurityGuarder.ini";
            var iniParser = new IniParser(iniFilePath, new Observe_err());
            string? _SecretId = null;
            string? _SecretKey = null;
            string? _region = null;
            try
            {
                _SecretId = iniParser.GetSetting("_SecretId") ?? throw new Exception("缺少参数: _SecretId");
                _SecretKey = iniParser.GetSetting("_SecretKey") ?? throw new Exception("缺少参数: _SecretKey");
                _region = iniParser.GetSetting("region") ?? throw new Exception("缺少参数: region");
            }
            catch (Exception e)
            {
                //应该做一下观察器，我就算了懒得麻烦
                MessageBox.Show(e.Message);
                StaticLogWrite.Logger.Log(LogLevel.Error, e.Message);
            }
            Credential cred = new Credential
            {
                SecretId = _SecretId,
                SecretKey = _SecretKey,
                //SecretId = "AKIDUwaIC1jHj15uVt34teHg3E8uTr5EF8tU",
                //SecretKey = "e2GPV1VwC6tUt3y64pXIuOWeiaEj06Rx"
            };
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
             clientProfile = new ClientProfile();
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
             httpProfile = new HttpProfile();
            httpProfile.Endpoint = ("bda.tencentcloudapi.com");
            clientProfile.HttpProfile = httpProfile;
            // 实例化要请求产品的client对象,clientProfile是可选的
            //region = "ap-guangzhou"
            client = new BdaClient(cred,_region , clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
             req = new DetectBodyJointsRequest();
          
        }
        ///Interface------------------------------------------------------------------------------------------------------------------------

        public bool GetSafe()
        {
            return _last_issafe;
        }
        public void Stop_SecurityGuarder()
        {
            _isRun=false;
        }
        public void Start_SecurityGuarder()
        {
            _isRun = true;
        }


    }
}
            